from django.template import Library
from django.conf import settings

# 创建注册中心
register = Library()


@register.inclusion_tag("tag/breadcrumb.html")
def breadcrumb(request):
    """ 路径导航 """
    # 1.获取当前用户对应的权限字典
    role = request.user_info["role"]
    permission_dict = settings.PERMISSION_DICT[role]

    # 2.根据当前路由生成路径导航列表
    path_nav_list = []  # 返回列表：[{"name": "home", "text": "首页"}, {...}]
    # 获取当前url的name 以及 该name对应的字典
    curr_url_name = request.resolver_match.url_name
    curr_url_dict = permission_dict[curr_url_name]
    # 将当前url的name和text添加到路径导航列表中
    path_nav_list.append({"name": curr_url_name, "text": curr_url_dict["text"]})
    # 循环
    parent = curr_url_dict["parent"]
    while parent:
        curr_url_dict = permission_dict[parent]
        path_nav_list.insert(0, {"name": parent, "text": curr_url_dict["text"]})
        parent = curr_url_dict["parent"]

    return {"path_nav_list": path_nav_list}



@register.filter
def has_permission(request, name):
    """ 颗粒控制按钮 """
    # 获取该用户权限
    role = request.user_info['role']
    permission_dict = settings.PERMISSION_DICT[role]

    # 权限校验
    if name in permission_dict:
        return True

    return False
